package com.syt.dome.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.syt.dome.repository.DepartmentRepository;
import com.syt.dome.repository.HospitalRepository;
import com.syt.dome.service.HospitalService;
import com.syt.entity.enums.DictEnum;
import com.syt.entity.model.hosp.Department;
import com.syt.entity.model.hosp.Hospital;
import com.syt.entity.vo.hosp.HospitalQueryVo;
import com.syt.smn.cliert.DictFeignClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {


    @Autowired
    private HospitalRepository hospitalRepository;


    @Autowired
    private DictFeignClient dictFeignClient;// 远程调用接口

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }



    //    根据医院编号获取详情信息
    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        //医院详情
        Hospital hospital = this.setHospitalHosType(this.getByHoscode(hoscode));
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;

    }



    // 根据医院名称获取医院列表
    @Override
    public List<Hospital> findByHosname(String hosname) {

        // 直接返回
        return  hospitalRepository.findHospitalByHosnameLike(hosname);
    }



    //     // 根据医院编号 获取医院名称 副本
    @Override
    public String getHospNames(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if(null != hospital) {
            return hospital.getHosname();
        }
        return "";
    }



    // 根据医院编号 获取医院名称
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if(null != hospital) {
            return hospital.getHosname();
        }
        return "";

    }



// 更新医院的上线状态
    @Override
    public void updateStatus(String id, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            // 根据 id 查询医院信息
            Hospital hospital = hospitalRepository.findById(id).get();
            // 设置修改的值
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }


    }

//  查看医院详情信息
    @Override
    public Map<String, Object> getHospById(String id) {
        // Hospital hospital = hospitalRepository.findById(id).get();
        // 将内容放到map集合中
        HashMap<String, Object> hashMap = new HashMap<>();

        Hospital hospitalHosType = this.setHospitalHosType( hospitalRepository.findById(id).get());
// 医院的基本信息(包含医院等级)
        hashMap.put("hospitalHosType",hospitalHosType);

//单独处理更直观
        hashMap.put("bookingRule", hospitalHosType.getBookingRule());
//不需要重复返回
        hospitalHosType.setBookingRule(null);

        return hashMap;
    }



/*
查看医院详情信息  课件中的方法
    @Override
    public Map<String, Object> show(String id) {
        Map<String, Object> result = new HashMap<>();

        Hospital hospital = this.packHospital(this.getById(id));
        result.put("hospital", hospital);

//单独处理更直观
        result.put("bookingRule", hospital.getBookingRule());
//不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }*/




/*
    @Override
    public Page<Hospital> selectHospPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
//0为第一页
        Pageable pageable = PageRequest.of(page-1, limit, sort);

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);

//创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //创建实例
        Example<Hospital> example = Example.of(hospital, matcher);
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);

        pages.getContent().stream().forEach(item -> {
            this.packHospital(item);
        });
        return pages;
    }

    */
/**
     * 封装数据
     * @param
      //hospital
     * @return
     *//*

    private Hospital packHospital(Hospital hospital) {
        String hostypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(),hospital.getHostype());
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());

        hospital.getParam().put("hostypeString", hostypeString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;
    }


*/
















    // 医院列表（条件查询分页）
    @Override
    public Page<Hospital> selectHospPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {

        // 创建 pageable 对象
        Pageable pageable = PageRequest.of(page - 1, limit);// 分页 当前页 每页记录数

        //创建条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        // hospitalQueryVo 转换成 hospital对象
        Hospital hospital=new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);


        //创建对象
        Example<Hospital> example = Example.of(hospital);// 传入对象 条件匹配器


        // 调用方法
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);




      // 获取查询list集合，遍历 进行医院等级封装
        pages.getContent().stream().forEach(item->{

            this.setHospitalHosType(item);

        });
        return pages;
    }






  /*  //医院列表(条件查询分页)
    @Override
    public Page<Hospital> selectHospPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //创建pageable对象
        Pageable pageable = PageRequest.of(page-1,limit);
        //创建条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        //hospitalSetQueryVo转换Hospital对象
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        //创建对象
        Example<Hospital> example = Example.of(hospital,matcher);
        //调用方法实现查询
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);

        //获取查询list集合，遍历进行医院等级封装
        pages.getContent().stream().forEach(item -> {
            this.setHospitalHosType(item);
        });

        return pages;
    }

*/





    // 封装数据
    // 获取查询list集合，遍历 进行医院等级封装 封装条件
    private Hospital setHospitalHosType(Hospital hospital) {

        // 根据 dictCode和value 获取医院等级信息
        String hostypeString = dictFeignClient.getName("Hostype", hospital.getHostype());
        // 查询省 市 地区
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());// 省
        String cityCodeString = dictFeignClient.getName(hospital.getCityCode());// 市
        String districtCodeString = dictFeignClient.getName(hospital.getDistrictCode());// 地区
         // 查询地区的值
        hospital.getParam().put("fullAddress",provinceString+cityCodeString+districtCodeString);

        hospital.getParam().put("hostypeString",hostypeString);

        return hospital;

    }










    // 上传医院接口的方法
    @Override
    public void save(Map<String, Object> stringObjectMap) {

        // 把参数 map 集合转换对象 hospital
        String jsonString = JSONObject.toJSONString(stringObjectMap);
        Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);
        // 判断是否存在相同的数据
        String hoscode = hospital.getHoscode();

        Hospital hospitalExist = hospitalRepository.getHospitalByHoscode(hoscode);


        if (hospitalExist != null) {
            // 存在，进行更新修改操作
            hospital.setStatus(hospitalExist.getStatus());
            hospital.setCreateTime(hospitalExist.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);

            hospitalRepository.save(hospital);
        } else {
            // 不存在，进行添加
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);

            hospitalRepository.save(hospital);
        }


    }

    // 调用service 方法实现根据医院编号查询
    @Override
    public Hospital getByHoscode(String hoscode) {


        Hospital hospitalByHoscode = hospitalRepository.getHospitalByHoscode(hoscode);
        return hospitalByHoscode;
    }


}
